package gientech.spring.CallRestfulDemo.controller;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

/**
 * @author Administrator
 * @title: CallRemote
 * @projectName CallRestfulDemo
 * @description: TODO
 * @date 2022/9/812:49
 */
@RequestMapping("/remote")
@Controller
public class CallRemoteController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = "/callRemote1")
    @ResponseBody
    public String queryCoffeeByName(@RequestParam("coffeeName") String coffeeName) {
        System.out.println("hello  callRemote1");
        return  restTemplate.getForObject("http://192.168.0.103:8080/restful/queryCoffeeByName?coffeeName=mocha", String.class);
    }


    @RequestMapping(value = "/callRemote2")
    @ResponseBody
    public String queryCoffeeByName2(@RequestParam("coffeeName") String coffeeName) throws IOException {
        System.out.println("hello callRemote2");
        String urlParam = "http://192.168.0.103:8080/restful/queryCoffeeByName?coffeeName=mocha";

        HttpClient httpClient = new HttpClient();

        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);

        GetMethod getMethod = new GetMethod(urlParam);

        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
        getMethod.addRequestHeader("Content-Type", "application/json");

        httpClient.executeMethod(getMethod);

        String result = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
        System.out.println("queryCoffeeByName2 : " + result);
        return result;

    }

    @RequestMapping(value = "/callRemote3")
    @ResponseBody
    public String queryCoffeeByName3(@RequestParam("coffeeName") String coffeeName) throws IOException {
        System.out.println("hello  callRemote3");
        String urlParam = "http://192.168.0.103:8080/restful/queryCoffeeByName?coffeeName=mocha";

        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(urlParam);
            connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("GET");

            connection.setReadTimeout(15000);

            connection.connect();

            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();

    }


    @RequestMapping(value = "/callRemote4")
    @ResponseBody
    public String queryCoffeeByName4(@RequestParam("coffeeName") String coffeeName) throws IOException {
        System.out.println("hello callRemote4");
        String urlParam = "http://192.168.0.103:8080/restful/queryCoffeeByName?coffeeName=mocha";

        Request request;
        final Request.Builder builder = new Request.Builder().url(urlParam);
        String result = null;
        try {
            request = builder.build();
            okhttp3.OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            result = response.body().string();
            System.out.println("queryCoffeeByName4 : " + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }






    @RequestMapping(value = "/callRemote5")
    @ResponseBody
    public String queryCoffeeByName5(@RequestParam("coffeeName") String coffeeName) throws IOException {
        System.out.println("hello callRemote5");
        String urlParam = "http://192.168.0.103:8080/restful/queryCoffeeByName?coffeeName=mocha";

        StringBuilder builder = new StringBuilder();
        try (CloseableHttpClient client = HttpClientBuilder.create().build()) {

            HttpGet request = new HttpGet(urlParam);
            HttpResponse response = client.execute(request);

            BufferedReader bufReader = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));

            String line = null;
            while ((line = bufReader.readLine()) != null) {
                builder.append(line);
                builder.append(System.lineSeparator());
            }
            System.out.println("queryCoffeeByName5 : " + builder.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
        return builder.toString();
    }

    // 还有其他方式，如java11 HttpClient，Socket，Unirest 等等其他方式
}
